//
//  RemoteMenuDetail.m
//  X-Touch2
//
//  Created by shengchao yang on 12-3-19.
//  Copyright (c) 2012年 foxhis. All rights reserved.
//

#import "RemoteMenuDetail.h"
#import "DetailTableViewCell.h"
#import "Singleton.h"
#import "FileManager.h"
#import "Common.h"
#import "DetailTableViewSectionController.h"

#import "Http.h"
#import "JSON.h"
#import "DownloadFromInternet.h"
#import "MAlertView.h"

@implementation RemoteMenuDetail
@synthesize indicator;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}
- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

#pragma mark - datasource
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return AppSession.remoteSortedMenus.count + 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString * key=@"其它";
    if (section<AppSession.remoteSortedMenus.count) {
        PluSort *tempSort = (PluSort *)[AppSession.remoteSortedMenus objectAtIndex:section];
        key = JsonField(tempSort.psDescripts);
    }
    return key;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    
    NSString * key=@"其它";
    if (section<AppSession.remoteSortedMenus.count) {
        PluSort *tempSort = (PluSort *)[AppSession.remoteSortedMenus objectAtIndex:section];
        key = [NSString stringWithFormat:@"%@[%@]",JsonField(tempSort.psDescripts),tempSort.psCode];
    }
    NSMutableArray * tempArray = (NSMutableArray *)[AppSession.remoteSortedDishes objectForKey:key];
    return tempArray.count;
}
//自定义row
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"CellIdentifier";    
	DetailTableViewCell *cell = (DetailTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil){
		cell = [[[DetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
	}    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;//设置选择cell时，没有任何背景颜色
    cell.tag = TagOfUITableViewCell + indexPath.row;
    
    NSString * key=@"其它";
    if (indexPath.section<AppSession.remoteSortedMenus.count) {
        PluSort *tempSort = (PluSort *)[AppSession.remoteSortedMenus objectAtIndex:indexPath.section];
        key = [NSString stringWithFormat:@"%@[%@]",JsonField(tempSort.psDescripts),tempSort.psCode];
    }
    NSMutableArray * tempArray = (NSMutableArray *)[AppSession.remoteSortedDishes objectForKey:key];
    [cell setData:(RemoteDishes *)[tempArray objectAtIndex:indexPath.row]];
    return cell;
}
#pragma mark - datadelegate
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MyNSLog(@"selected index=%d", indexPath.row);
}

- (IBAction)buttonClicked:(id)sender {
    if (AppSession.isAnimating) {
        UIAlertView *alert =[[ UIAlertView alloc] initWithTitle:TranslateStr(@"正在查询中...") 
                                                        message:nil
                                                       delegate:nil 
                                              cancelButtonTitle:TranslateStr(@"返回") 
                                              otherButtonTitles: nil];
        [alert show];
        [alert release];
        return;
    }
    
    [AppSession playMusic:VoiceFile(@"clicked.caf")];
    NSInteger bid = [sender tag];
    if (bid == TagOfUIButton) {
        //弹出对话确认框
        NSString * msg = [NSString stringWithFormat:@"%@：%@[%@]",TranslateStr(@"桌号"),JsonField(_currentRemoteMenu.rmTableDescripts),_currentRemoteMenu.rmTableNo];
        MAlertView *alert =[[ MAlertView alloc] initWithTitle:TranslateStr(@"送单确认") 
                                                      message:msg
                                                     delegate:self 
                                            cancelButtonTitle:TranslateStr(@"取消") 
                                            otherButtonTitles:TranslateStr(@"确定"), nil];
        UITextField * username = [[UITextField new] autorelease];
        username.tag = TagOfUITextField;
        UITextField * password = [[UITextField new] autorelease];
        password.tag = TagOfUITextField + 1;
        password.secureTextEntry = YES;
        [alert addTextField:username placeHolder:TranslateStr(@"用户名")];
        [alert addTextField:password placeHolder:TranslateStr(@"密码")];
        [alert show];
        [alert release];  
    }else if(bid == TagOfUIButton + 1){
        NSString *SysMsg = [NSString stringWithFormat:@"SysMsg_MessageBoxBaseView_%@", self.nibName];
        postN(SysMsg);//关闭弹出窗口
//        [self.view removeFromSuperview];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
    if (buttonIndex == alertView.firstOtherButtonIndex) {//清空我的点单数据
        UITextField * userField = (UITextField *)[alertView viewWithTag:TagOfUITextField];
        UITextField * passField = (UITextField *)[alertView viewWithTag:TagOfUITextField+1];
        NSString * empno = FormatNilObject(userField.text);
        NSString * password = FormatNilObject(passField.text);
        
        //弹出正在处理窗口
        NSDictionary *infos = [NSDictionary dictionaryWithObjectsAndKeys:TranslateStr(@"正在发送"),@"message",nil];
        postNWithInfos(@"SysMsg_RootView_ShowMyProcessView", self, infos);
        NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:empno,@"empno",password,@"password", nil];
        
        NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(startSendMyOrder:) object:dict];
        [thread start];//启动更新入口
        [thread release];  
        
              
    }
}

-(void) startSendMyOrder:(NSDictionary *)obj{   
    NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
    NSString * empno = [obj objectForKey:@"empno"];
    NSString * password = [obj objectForKey:@"password"];
    NSString * persons = @"0";
    NSString * tableno = AppSession.currentOrderMenu.ptTableNo;
    NSString * UDID = AppSession.ipadUdid;
    NSString *sendOrderJson=[NSString stringWithFormat:@"{\"empno\":\"%@\",\"password\":\"%@\",\"persons\":\"%@\",\"tableno\":\"%@\",\"UDID\":\"%@\",\"myorders\":",empno,password,persons,tableno,UDID];
    
    //组装我的点单json串
    NSString *myorderJson=@"[";
//        myorderJson=[myorderJson stringByAppendingFormat:@"{\"ppCode\":\"%@\",",temp.ppCode];
//        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppName\":\"%@\",",JsonField(temp.modDescripts)];
//        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppNumber\":\"%@\",",temp.modNumber];
//        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppPrice\":\"%@\",",temp.modPrice];
//        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppUnit\":\"%@\",",JsonField(temp.modUnits)];
//        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppCook\":\"%@\",",temp.modCook];
//        myorderJson=[myorderJson stringByAppendingFormat:@"\"ppTemp\":\"%@\"}",temp.modPluPlu.ppTemp];
//        if (indexMyOrder<[AppSession.myOrderDishes count]) {
//            myorderJson=[myorderJson stringByAppendingFormat:@","];
//        }        
    sendOrderJson=[sendOrderJson stringByAppendingFormat:@"%@]}",myorderJson];//最终要发送的json串
    MyNSLog(@"sendOrderJson=%@", sendOrderJson);
    
    //接收返回信息 
    NSError *outError = nil;
    NSString *sendResult = [DownloadFromInternet sendMyOrders:sendOrderJson Error:&outError];
    NSDictionary *resultDic = [sendResult JSONValue];
    NSString *errCode = @"";
    NSString *errMsg = @"";
    if ([resultDic count]==0) {
        errCode=@"88888";
        errMsg=@"送单失败！请检查网络是否连接以及网站接口是否开启！";//[NSString stringWithFormat:@"%@\r\n%@",[outError localizedDescription],sendResult];
    }
    else{
        errCode=[resultDic objectForKey:@"code"];
        errMsg=[resultDic objectForKey:@"message"];
    }
    MyNSLog(@"sendResult=%@",sendResult);
    
    //返回结果处理
    postN(@"SysMsg_RootView_CloseMyProcessView");//关闭弹出窗口
    NSString * alertTitle = @"送单失败！";
    NSString * alertMessage = [NSString stringWithFormat:@"(%@)%@",errCode,errMsg];
    if ([errCode isEqualToString:@"30002"]) {//送单成功!
        alertTitle = @"送单成功！";        
        NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(startDownload) object:nil];
        [thread start];//刷新界面
        [thread release]; 
    }
    
    UIAlertView *alert1 =[[ UIAlertView alloc] initWithTitle:alertTitle
                                                     message:alertMessage
                                                    delegate:nil 
                                           cancelButtonTitle:TranslateStr(@"确定")
                                           otherButtonTitles:nil];
    [alert1 show];
    [alert1 release];
    [pool release];
}
#pragma mark - View lifecycle
- (void)viewDidLoad{
    [super viewDidLoad];
    _remoteOrderTable = (UITableView *)[self.view viewWithTag:TagOfUITableView];
    [_remoteOrderTable setDelegate:self];
    [_remoteOrderTable setDataSource:self];
    
    [DataBaseAccess Update:@"delete from RemoteDishes"];//删除本地数据库里的远程主单记录  
    _currentRemoteMenu = (RemoteMenus *)[AppSession.remoteMenus objectAtIndex:AppSession.remoteMenuIndex];
    [AppSession initRemoteDishes];//初始化远程主单明细
    
    lblCompanyName = (UILabel *)[self.view viewWithTag:TagOfUILabel];
    lblTableNo = (UILabel *)[self.view viewWithTag:TagOfUILabel+1];
    lblPersons = (UILabel *)[self.view viewWithTag:TagOfUILabel+2];
    lblDate = (UILabel *)[self.view viewWithTag:TagOfUILabel+3];//开单时间
    lblEmpno = (UILabel *)[self.view viewWithTag:TagOfUILabel+4];
    lblAmount = (UILabel *)[self.view viewWithTag:TagOfUILabel+5];
    lblStatus = (UILabel *)[self.view viewWithTag:TagOfUILabel+6];
    
    //初始化数据
    lblCompanyName.text = AppSession.hotelName;
    lblTableNo.text = _currentRemoteMenu.rmTableNo;
    lblPersons.text = _currentRemoteMenu.rmPersons; 
    lblDate.text = _currentRemoteMenu.rmDate;
    lblEmpno.text = _currentRemoteMenu.rmEmpno;
    lblAmount.text = _currentRemoteMenu.rmAmount;
    
    
    
    NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(startDownload) object:nil];
    [thread start];//启动更新入口
    [thread release];
}

-(void)startDownload {
    NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
    [DataBaseAccess Update:@"delete from RemoteDishes"];//删除本地数据库里的远程主单记录    
    lblStatus.text = @"正在查询...";
    lblStatus.textColor = indicator.color = [UIColor redColor];
    [indicator startAnimating];
    AppSession.isAnimating = YES;
    [Common downLoadRemoteDishes:_currentRemoteMenu.rmMenu]; 
    [AppSession initRemoteDishes];//初始化远程主单明细
    [(UITableView *)[self.view viewWithTag:TagOfUITableView] reloadData];//刷新界面
    AppSession.isAnimating = NO;
    if (AppSession.remoteSortedMenus.count == 0) {
        lblStatus.text = @"查询失败！";
        lblStatus.textColor = indicator.color = [UIColor redColor];
    }else {
        lblStatus.text = @"查询成功！";
        lblStatus.textColor = indicator.color = [UIColor blueColor];
    }
    
    [indicator stopAnimating];
    [pool release];
}

- (void)viewDidUnload{
    [self setIndicator:nil];
    [super viewDidUnload];
}
-(void)dealloc{
    MyNSLog(@"RemoteMenuDetail is deallocing...");
    [indicator release];
    [super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
@end
